/*
 * @Author: your name
 * @Date: 2021-03-29 10:21:23
 * @LastEditTime: 2021-03-30 13:36:46
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /egg-ts/app/extend/helper.ts
 */
import { Buffer } from 'buffer';
import crypto = require('crypto');
import fs = require('fs');
import path = require('path');
import jwt = require('jsonwebtoken');

/**
 *  MD5加密
 **/
export const Md5 = function(data) {
  const buf = new Buffer(data);
  const str = buf.toString('binary');
  return crypto.createHash('md5').update(str).digest('hex');
};

/**
 * 随机数
 * */
export const Random = function(m, n) {
  return Math.floor(Math.random() * (m - n) + n);
};

/**
 * 用户授权 authorization
 * */
export const Authorization = function(ctx) {
  if (ctx.session.populated && ctx.session.user !== undefined) {
    return true;
  }
  return false;
};

/**
 * token生成
 */
export const loginToken = function(_ctx, data, expires = 60 * 60 * 24) {
  const exp = Math.floor(Date.now() / 1000) + expires;
  const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_private_key.pem')); // 私钥，看后面生成方法
  const token = jwt.sign({ data, exp }, cert, { algorithm: 'RS256' });
  return token;
};


// 解密，验证
export function verifyToken(token) {
  const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_private_key.pem')); // 公钥，看后面生成方法
  let res = '';
  try {
    const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {};
    const { exp } = result,
      current = Math.floor(Date.now() / 1000);
    if (current <= exp) res = result.data || {};
  } catch (e) {
    console.log(e);
  }
  return res;
}
